package com.qf.controller;

import com.qf.pojo.User;
import com.qf.pojo.UserAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author wbzs,
 * @date 2022/10/19,
 * @time 23:00,
 */
@RestController
@RequestMapping("/user")
public class UserController {


    //负载均衡的客户端你，此处就是为了演示xi效果
    @Autowired
    private LoadBalancerClient loadBalancedClient;


    private RestTemplate restTemplate;

    @Autowired
    public UserController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @RequestMapping("info/{id}")
    public User findByid( @PathVariable Integer id){
        System.out.println("我进来啦");

        User user = new User();
        user.setId(id);
        user.setName("张飞");
        //需要地址信息，地址需要找地址的程序获取
        /**
         * 参数一：我们的请求地址
         * 参数二：我们期望网络请求返回的数据解析为什么类型
         * 参数三：有没有key=value格式的参数
         *
         */

        //从注册中心获取地址，这里的域名就换成了我们想要请求的程序在eureka的名字
        UserAddress userAddress = restTemplate.getForObject("http://ADDRESSPROVIDEREUREKA04/address/info/" + id, UserAddress.class);
        user.setUserAddress(userAddress);
        return user;

    }

    @GetMapping("/load")
    public  int testLoadBlance(){

        ServiceInstance addressprovidereureka04 = loadBalancedClient.choose("addressprovidereureka04");
        ServiceInstance addressprovidereureka041 = loadBalancedClient.choose("addressprovidereureka041");
        int port1 = addressprovidereureka041.getPort();
        int port = addressprovidereureka04.getPort();
        System.out.println(port+"->"+port1);
        return port;
    }

}
